package com.hundsun.yr.universal.p2p.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.view.BrowserLayout;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog.HSDialogOnItemClickListener;
import com.hundsun.yr.universal.p2p.bean.BankAccountBeen;
import com.hundsun.yr.universal.p2p.bean.ManeBean;
import com.hundsun.yr.universal.p2p.bean.MineInvestProtocolBean;
import com.hundsun.yr.universal.p2p.bean.UpdatePayPwdBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @version V1.0
 * @Title: MineBankCardActivity.java
 * @Description: 银行卡 没有银行卡信息的时候去绑定银行卡信息，有银行卡信息的时候显示银行卡信息
 * @date 2016-1-18 下午7:22:38
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class MineBankCardActivity extends BaseActivity implements OnClickListener, InitializeView, HSDialogOnItemClickListener {

    /**
     * 有卡的布局
     **/
    private LinearLayout linear_card = null;

    /**
     * 无卡的布局
     */
    private LinearLayout linear_nocard = null;

    /**
     * 请求接口
     **/
    private static RequestPresenter mPresenter = null;
//    /**
//     * 银行卡号
//     **/
//    private String cardNo = null;
    /**
     * 解绑弹窗弹窗
     **/
    private HSDialog dialog_unbind = null;
//    /**
//     * 绑定的卡号
//     **/
//    private String bindCard = "";

    /**
     * 中网时间
     */
    private String zwgt_data;

    private BrowserLayout mBrowserLayout = null;
    private BankAccountBeen bankAccountBeen;
    private HSDialog paypwdDialog = null;
    /**
     * bindcard
     */
    private ImageView iv_bind_card = null;

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return true;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_bank_card;
    }

    @Override
    protected void initViewsAndEvents() {
        setToolbarTitle(R.string.bankcard);

        linear_card = findView(R.id.linear_card);
        linear_nocard = findView(R.id.linear_nocard);
        mBrowserLayout = findView(R.id.bl_browserLayout);
        iv_bind_card = findView(R.id.iv_bind_card);

        if (sharedPreferences.getShareProf(UserInfo.IF_BINDCARD).equals("YES")) {
            linear_card.setVisibility(View.VISIBLE);
            linear_nocard.setVisibility(View.GONE);
            toolbar_menu.setText(R.string.unbind);
            toolbar_menu.setTextColor(Color.BLACK);
            toolbar_menu.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            toolbar_menu.setOnClickListener(this);
            mPresenter = new InitializePresenterImpl(this, this);
            loadingData();
        } else {
            linear_card.setVisibility(View.GONE);
            linear_nocard.setVisibility(View.VISIBLE);
            iv_bind_card.setOnClickListener(this);
            mPresenter = new InitializePresenterImpl(mContext, this);
        }
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    /**
     * 获取银行卡信息
     */
    private void loadingData() {
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        HashMap<String, String> hearder = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                TaskConstants.TASK_MYBANKCARD, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);

        mBrowserLayout.hideBrowserController();
        mBrowserLayout.setVerticalScrollBarEnabled(false);
        mBrowserLayout.setHorizontalScrollBarEnabled(false);
        mBrowserLayout.loadUrl(getString(R.string.root_h5_url_test) + getString(R.string.h5_user) + TaskConstants.TASK_MYBANKCARD, hearder);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
//        bindCard = (String) extras.get("bindCard");
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
    }


    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void onNetworkConnected(NetType type) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onNetworkDisConnected() {
        // TODO Auto-generated method stub

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_menu:// 解绑
                dialog_unbind = new HSDialog(null, getString(R.string.tips_unbind), getString(R.string.cancel),
                        getString(R.string.sure), this, this).setCancelable(false);//.setOnDismissListener(this);
                dialog_unbind.show();
                break;

            case R.id.iv_bind_card:
                //readyGo(BindCardActivity.class);
                if (TextUtils.equals(sharedPreferences.getShareProf(UserInfo.IF_PAYPWD), "YES")) {
                    bindCar();
                } else {
                    paypwdDialog = new HSDialog(getString(R.string.tips), getString(R.string.tips_nopaypwd),
                            getString(R.string.cancel), getString(R.string.tips_go_set), mContext, this).setCancelable(false);
                    paypwdDialog.show();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.TASK_BANK_ACCOUNT, getString(R.string.root_url_test) + getString(R.string.api_user_test) +
                TaskConstants.TASK_BANK_ACCOUNT, Constants.EVENT_BEGIN, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test)
                + TaskConstants.TASK_BANK_ACCOUNT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @SuppressWarnings("rawtypes")
    @Override
    public <T> void initializeViews(String task_name, T data) {
        switch (task_name) {
            case TaskConstants.TASK_CARDUNBIND:
                MineInvestProtocolBean bean = (MineInvestProtocolBean) data;
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                        "untie", sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap2 = new HeaderMap();
                headerMap2.setMap(hearder);
                Bundle bundler = new Bundle();
                bundler.putString(BaseWebActivity.BUNDLE_KEY_URL, bean.getHtml());
                bundler.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap2);
//                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_TITLE, zwgt_data);
                bundler.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
                readyGoThenKill(WebOpenAccountActivity.class, bundler);
//                mPresenter.loadingData(TaskConstants.TASK_BANK_ACCOUNT, getString(R.string.root_url_test) + getString(R.string.api_user_test) +
//                        TaskConstants.TASK_BANK_ACCOUNT, Constants.EVENT_BEGIN, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test)
//                        + TaskConstants.TASK_BANK_ACCOUNT, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
                break;
            case TaskConstants.TASK_BANK_ACCOUNT:
                //查询托管账户信息，更新ui
                bankAccountBeen = (BankAccountBeen) data;
                //保存余额信息
//                sharedPreferences.putShareProf(UserInfo.CAN_USE_MONEY, bankAccountBeen.availBal);

                //对江西银行卡信息进行显示
                if (!bankAccountBeen.depository_bank_no.isEmpty()) {//如果返回有银行卡信息，则将银行卡信息保存并且显示银行卡
                    //将获得的银行卡信息保存
                    sharedPreferences.putShareProf(UserInfo.JX_ACCOUNT_NO, bankAccountBeen.depository_bank_no);
                }

                //如果获取了用户的银行卡信息就将其绑定
                /**存储开户信息**/
                if (bankAccountBeen.depository_bank_no != null && !bankAccountBeen.depository_bank_no.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.JIANGXI_BANKCARD, bankAccountBeen.depository_bank_no);
                    sharedPreferences.putShareProf(UserInfo.IF_ACCOUNT, "YES");
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_ACCOUNT, "NO");
                }

                /**存储绑卡信息**/
                if (bankAccountBeen.bankCard != null && !bankAccountBeen.bankCard.isEmpty() && bankAccountBeen.bankName != null && !bankAccountBeen.bankName.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.BANKCARD, bankAccountBeen.bankCard);
                    sharedPreferences.putShareProf(UserInfo.BANKCARDNAME, bankAccountBeen.bankName);

                    sharedPreferences.putShareProf(UserInfo.IF_BINDCARD, "YES");
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_BINDCARD, "NO");
                }

                if (bankAccountBeen.true_name != null && !bankAccountBeen.true_name.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.REAL_USER_NAME, bankAccountBeen.true_name);
                }

                /**
                 * 绑定身份证
                 */
                if (bankAccountBeen.cert_no != null && !bankAccountBeen.cert_no.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.CERT_NO, bankAccountBeen.cert_no);
                }

                /**保存登陆手机号**/
                //保存手机号码
                if (bankAccountBeen.phone != null && !bankAccountBeen.phone.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.MOBILE, bankAccountBeen.phone);
                }

                /*            *//**保存用户交易密码设置状态**/
                if (bankAccountBeen.set_paypwd_flag != null && !bankAccountBeen.set_paypwd_flag.isEmpty()) {
                    if (TextUtils.equals(bankAccountBeen.set_paypwd_flag, "1")) {
                        //已经设置交易密码
                        sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "YES");
                    } else {
                        sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                    }
                } else {
                    sharedPreferences.putShareProf(UserInfo.IF_PAYPWD, "NO");
                }

                /**保存可用余额**/
                if (bankAccountBeen.availBal != null && !bankAccountBeen.availBal.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.CAN_USE_MONEY, bankAccountBeen.availBal);
                }

                //保存用户vip等级
                if (bankAccountBeen.vip != null && !bankAccountBeen.vip.isEmpty()) {
                    sharedPreferences.putShareProf(UserInfo.VIPLEVEL, bankAccountBeen.vip);
                }

                // finish();
                if (sharedPreferences.getShareProf(UserInfo.IF_BINDCARD).equals("YES")) {
                    linear_card.setVisibility(View.VISIBLE);
                    linear_nocard.setVisibility(View.GONE);
                    toolbar_menu.setText(R.string.unbind);
                    toolbar_menu.setTextColor(Color.BLACK);
                    toolbar_menu.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                    toolbar_menu.setOnClickListener(this);
                    mPresenter = new InitializePresenterImpl(this, this);
                    loadingData();
                } else {
                    linear_card.setVisibility(View.GONE);
                    linear_nocard.setVisibility(View.VISIBLE);
                    iv_bind_card.setOnClickListener(this);
                    mPresenter = new InitializePresenterImpl(mContext, this);
                }
                break;
            case TaskConstants.TASK_CARDBIND:
                Gson gson = new Gson();
                ManeBean maneBean = gson.fromJson(String.valueOf(data), ManeBean.class);
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder1 = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                        "bindcardpagerst", sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap1 = new HeaderMap();
                headerMap1.setMap(hearder1);
                Bundle bundle = new Bundle();
                bundle.putString(BaseWebActivity.BUNDLE_KEY_URL, maneBean.getHtml());
                bundle.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap1);
                bundle.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
                readyGo(WebOpenAccountActivity.class, bundle);
                break;

            case TaskConstants.TASK_SETBANKPWD:
                if (data == null) {
                    return;
                }

                UpdatePayPwdBeen mUpdatePayPwdBeen = (UpdatePayPwdBeen) data;

                //现在做另外一种操作
                String postData = null;
                try {
                    postData = "accountId=" + URLEncoder.encode(mUpdatePayPwdBeen.data.accountId.toString(), "utf-8") + "&acqRes=" + URLEncoder.encode(mUpdatePayPwdBeen.data.acqRes.toString(), "utf-8") +
                            "&bankCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.bankCode.toString(), "utf-8") + "&channel=" + URLEncoder.encode(mUpdatePayPwdBeen.data.channel.toString(), "utf-8") +
                            "&idNo=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idNo.toString(), "utf-8") + "&idType=" + URLEncoder.encode(mUpdatePayPwdBeen.data.idType.toString(), "utf-8") + "&instCode=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.instCode.toString(), "utf-8") + "&lastSrvAuthCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.lastSrvAuthCode == null ? "" : mUpdatePayPwdBeen.data.lastSrvAuthCode.toString(), "utf-8") +
                            "&mobile=" + URLEncoder.encode(mUpdatePayPwdBeen.data.mobile.toString(), "utf-8") + "&name=" + URLEncoder.encode(mUpdatePayPwdBeen.data.name.toString(), "utf-8") + "&notifyUrl=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.notifyUrl.toString(), "utf-8") + "&retUrl=" + URLEncoder.encode(mUpdatePayPwdBeen.data.retUrl.toString(), "utf-8") + "&seqNo=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.seqNo.toString(), "utf-8") + "&sign=" + URLEncoder.encode(mUpdatePayPwdBeen.data.sign.toString(), "utf-8") + "&smsCode=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.smsCode == null ? "" : mUpdatePayPwdBeen.data.smsCode.toString(), "utf-8") + "&txCode=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txCode.toString(), "utf-8") +
                            "&txDate=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txDate.toString(), "utf-8") + "&txTime=" + URLEncoder.encode(mUpdatePayPwdBeen.data.txTime.toString(), "utf-8") + "&version=" +
                            URLEncoder.encode(mUpdatePayPwdBeen.data.version.toString(), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                Bundle bundle1 = new Bundle();
                bundle1.putString(BaseWebActivity.BUNDLE_KEY_TITLE, getString(R.string.set_paywd));
                bundle1.putString(BaseWebActivity.BUNDLE_KEY_URL, mUpdatePayPwdBeen.url);
                bundle1.putString(BaseWebActivity.BUNDLE_KEY_PARAMS, postData);
                bundle1.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.POSTDATA.getIntValue());
                bundle1.putBoolean(BaseWebActivity.BUNDLE_KEY_SHOW_BOTTOM_BAR, false);
                readyGo(WebSetPasswordActivity.class, bundle1);
                break;
        }
    }

    @Override
    public <T> void initializeError(String task_name, T data) {
        // TODO Auto-generated method stub
        if (TextUtils.equals(task_name, TaskConstants.TASK_UNBIND)) {

        }
    }


    @Override
    public void onItemClick(Object o, int position) {
        //解卡，解卡成功的话，改变shareperence的状态ifbindcard bindcard什么什么的信息
        if ((HSDialog) o == dialog_unbind) {
            if (position != -1) {
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                mPresenter.loadingData(TaskConstants.TASK_CARDUNBIND, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_CARDUNBIND
                        , Constants.EVENT_DATA, new HashMap<String, String>(), BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_user_test) + TaskConstants.TASK_CARDUNBIND
                                , sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
            }
        } else if ((HSDialog) o == paypwdDialog) {
            if (position != -1) {
                readyGo(ManagementActivity.class);
            }
        }

    }

    private void bindCar() {
        //绑定银行卡
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
        mPresenter.loadingData(TaskConstants.TASK_CARDBIND, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_CARDBIND,
                Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_user_test) + TaskConstants.TASK_CARDBIND,
                        sharedPreferences.getShareProf(UserInfo.USER_NO),
                        sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

}
